package it.rockliveitalia;

import it.rockliveitalia.database.EventDbHelper;
import it.rockliveitalia.entity.Event;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.google.analytics.tracking.android.EasyTracker;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.text.InputType;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

public class EventFilterActivity extends Activity {

	private List<Event> eventList = new ArrayList<Event>();

	private CheckBox cbBand;
	private CheckBox cbVenue;
	private CheckBox cbDate;
	private CheckBox cbDateInterval;
	private EditText editText;
	private EditText editTextBis;
	private Button mapButton;
	private Button listButton;
	private String eventDateString = null;
	private String eventDateStringBis = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event_filter);

		cbBand = (CheckBox) findViewById(R.id.checkbox_band);
		cbVenue = (CheckBox) findViewById(R.id.checkbox_venue);
		cbDate = (CheckBox) findViewById(R.id.checkbox_date);
		cbDateInterval = (CheckBox) findViewById(R.id.checkbox_date_interval);
		editText = (EditText) findViewById(R.id.filter_edit_text);
		editTextBis = (EditText) findViewById(R.id.filter_edit_text_bis);
		mapButton = (Button) findViewById(R.id.filter_button_map);
		listButton = (Button) findViewById(R.id.filter_button_list);

		eventList = new ArrayList<Event>();
		EventDbHelper helper = new EventDbHelper(this);
		Cursor c = helper.getEvents();
		eventList.addAll(helper.cursorToEvents(c));
		helper.close();
	}

	@Override
	protected void onStart() {
		super.onStart();
		EasyTracker.getInstance(this).activityStart(this);
		clear();
	}

	@Override
	public void onStop() {
		super.onStop();
		EasyTracker.getInstance(this).activityStop(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	private List<String> venueFilter(String s) {
		List<String> result = new ArrayList<String>();
		EventDbHelper helper = new EventDbHelper(this);
		Cursor c = helper.getIDsFromVenue(s);
		result = helper.cursorToStrings(c);
		helper.close();
		return result;
	}

	private List<String> bandFilter(String s) {
		List<String> result = new ArrayList<String>();
		EventDbHelper helper = new EventDbHelper(this);
		Cursor c = helper.getIDsFromBand(s);
		result = helper.cursorToStrings(c);
		helper.close();
		return result;
	}

	private List<String> dateFilter(String s) {
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < eventList.size(); i++) {
			Event e = eventList.get(i);
			if (e.getStringDate().equals(s)) {
				result.add(e.getId());
			}
		}
		return result;
	}

	private List<String> intervalDateFilter(String date1, String date2) {
		List<String> result = new ArrayList<String>();
		Date d1, d2;
		Event event = new Event();
		event.setDate(date1);
		d1 = event.getDate();
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(d1);
		cal1.set(Calendar.HOUR_OF_DAY, 0);
		cal1.set(Calendar.MINUTE, 1);
		event.setDate(date2);
		d2 = event.getDate();
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(d2);
		cal2.set(Calendar.HOUR_OF_DAY, 23);
		cal2.set(Calendar.MINUTE, 59);
		EventDbHelper helper = new EventDbHelper(this);
		Cursor c = helper.getEventsByInterval(cal1.getTimeInMillis(),
				cal2.getTimeInMillis());
		result = helper.cursorToStrings(c);
		return result;
	}

	public void onCheckboxClicked(View view) {
		// Is the view now checked?
		boolean checked = ((CheckBox) view).isChecked();

		// Check which checkbox was clicked
		switch (view.getId()) {
		case R.id.checkbox_band:
			if (checked) {
				cbVenue.setChecked(false);
				cbDate.setChecked(false);
				cbDateInterval.setChecked(false);
				editText.setVisibility(View.VISIBLE);
				editTextBis.setVisibility(View.GONE);
				editText.setHint(R.string.insert_band);
				mapButton.setVisibility(View.VISIBLE);
				listButton.setVisibility(View.VISIBLE);
				editText.setText("");
				eventDateString = null;
				eventDateStringBis = null;
			} else {
				editText.setVisibility(View.GONE);
				mapButton.setVisibility(View.GONE);
				listButton.setVisibility(View.GONE);
				editText.setText("");
			}
			break;
		case R.id.checkbox_venue:
			if (checked) {
				cbDate.setChecked(false);
				cbBand.setChecked(false);
				cbDateInterval.setChecked(false);
				editText.setVisibility(View.VISIBLE);
				editTextBis.setVisibility(View.GONE);
				editText.setHint(R.string.insert_venue);
				mapButton.setVisibility(View.VISIBLE);
				listButton.setVisibility(View.VISIBLE);
				editText.setText("");
				eventDateString = null;
				eventDateStringBis = null;
			} else {
				editText.setVisibility(View.GONE);
				mapButton.setVisibility(View.GONE);
				listButton.setVisibility(View.GONE);
				editText.setText("");
			}
			break;
		case R.id.checkbox_date:
			if (checked) {
				cbVenue.setChecked(false);
				cbBand.setChecked(false);
				cbDateInterval.setChecked(false);
				editText.setVisibility(View.VISIBLE);
				editTextBis.setVisibility(View.GONE);
				editText.setHint(R.string.insert_date);
				mapButton.setVisibility(View.VISIBLE);
				listButton.setVisibility(View.VISIBLE);
				editText.setText("");
				eventDateStringBis = null;
			} else {
				editText.setVisibility(View.GONE);
				mapButton.setVisibility(View.GONE);
				listButton.setVisibility(View.GONE);
				editText.setText("");
			}
			break;
		case R.id.checkbox_date_interval:
			if (checked) {
				cbVenue.setChecked(false);
				cbBand.setChecked(false);
				cbDate.setChecked(false);
				editText.setVisibility(View.VISIBLE);
				editText.setHint(R.string.insert_from_date);
				editTextBis.setVisibility(View.VISIBLE);
				editTextBis.setHint(R.string.insert_to_date);
				mapButton.setVisibility(View.VISIBLE);
				listButton.setVisibility(View.VISIBLE);
				editText.setText("");
				editTextBis.setText("");
			} else {
				editText.setVisibility(View.GONE);
				editTextBis.setVisibility(View.GONE);
				mapButton.setVisibility(View.GONE);
				listButton.setVisibility(View.GONE);
				editText.setText("");
				editTextBis.setText("");
			}
			break;
		}
	}

	private void clear() {
		cbVenue.setChecked(false);
		cbBand.setChecked(false);
		cbDate.setChecked(false);
		cbDateInterval.setChecked(false);
		editText.setVisibility(View.GONE);
		editTextBis.setVisibility(View.GONE);
		mapButton.setVisibility(View.GONE);
		listButton.setVisibility(View.GONE);
		editText.setText("");
		editTextBis.setText("");
	}

	public void filterInput(View view) {
		if (cbBand.isChecked()) {
			showEditText(view, R.string.event_band_bis);
		} else if (cbVenue.isChecked()) {
			showEditText(view, R.string.event_venue_bis);
		} else if (cbDate.isChecked() || cbDateInterval.isChecked()) {
			showDatePicker(view);
		} else {

		}
	}

	public void showEditText(View v, int title) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		alert.setView(input);

		input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

		alert.setTitle(title);
		input.setText(editText.getText());
		alert.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						String value = input.getText().toString();
						editText.setText(value);

					}
				});

		alert.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.

					}
				});

		AlertDialog alertd = alert.create();
		alertd.getWindow().setSoftInputMode(
				LayoutParams.SOFT_INPUT_STATE_VISIBLE);
		alertd.show();
	}

	public void showDatePicker(View view) {
		// TODO Auto-generated method stub
		// To show current date in the datepicker
		Calendar mcurrentDate = Calendar.getInstance();
		int mYear = mcurrentDate.get(Calendar.YEAR);
		int mMonth = mcurrentDate.get(Calendar.MONTH);
		int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

		if (view.getId() == editText.getId()) {
			DatePickerDialog mDatePicker = new DatePickerDialog(
					EventFilterActivity.this, new OnDateSetListener() {
						public void onDateSet(DatePicker datepicker,
								int selectedyear, int selectedmonth,
								int selectedday) {
							// TODO Auto-generated method stub
							selectedmonth = selectedmonth + 1;
							eventDateString = selectedday + "/" + selectedmonth
									+ "/" + selectedyear;
							editText.setText(eventDateString);
						}
					}, mYear, mMonth, mDay);

			mDatePicker.setTitle(R.string.insert_date);
			mDatePicker.show();
		} else {
			DatePickerDialog mDatePicker = new DatePickerDialog(
					EventFilterActivity.this, new OnDateSetListener() {
						public void onDateSet(DatePicker datepicker,
								int selectedyear, int selectedmonth,
								int selectedday) {
							// TODO Auto-generated method stub
							selectedmonth = selectedmonth + 1;
							eventDateStringBis = selectedday + "/"
									+ selectedmonth + "/" + selectedyear;
							editTextBis.setText(eventDateStringBis);
						}
					}, mYear, mMonth, mDay);

			mDatePicker.setTitle(R.string.insert_date);
			mDatePicker.show();
		}
	}

	public void mapFilter(View view) {
		List<String> ids = new ArrayList<String>();
		if (cbBand.isChecked()) {
			if (!editText.getText().toString().equals("")) {
				ids = bandFilter(editText.getText().toString());
				if (ids.size() == 0) {
					noResults();
				} else {
					Intent intent = new Intent(this, MapFilterActivity.class);
					intent.putStringArrayListExtra("ids",
							(ArrayList<String>) ids);
					intent.putExtra("filter", editText.getText().toString());
					startActivity(intent);
				}
			} else {
				Toast.makeText(this, R.string.band_needed, Toast.LENGTH_SHORT)
						.show();
			}
		} else if (cbVenue.isChecked()) {
			if (!editText.getText().toString().equals("")) {
				ids = venueFilter(editText.getText().toString());
				if (ids.size() == 0) {
					noResults();
				} else {
					Intent intent = new Intent(this, MapFilterActivity.class);
					intent.putStringArrayListExtra("ids",
							(ArrayList<String>) ids);
					intent.putExtra("filter", editText.getText().toString());
					startActivity(intent);
				}

			} else {
				Toast.makeText(this, R.string.venue_needed, Toast.LENGTH_SHORT)
						.show();
			}
		} else if (cbDate.isChecked()) {
			if (eventDateString != null) {
				ids = dateFilter(eventDateString);
				if (ids.size() == 0) {
					noResults();
				} else {
					Intent intent = new Intent(this, MapFilterActivity.class);
					intent.putStringArrayListExtra("ids",
							(ArrayList<String>) ids);
					intent.putExtra("filter", editText.getText().toString());
					startActivity(intent);

				}
			} else {
				Toast.makeText(this, R.string.date_needed, Toast.LENGTH_SHORT)
						.show();
			}
		} else if (cbDateInterval.isChecked()) {
			if (eventDateString != null && eventDateStringBis != null) {
				ids = intervalDateFilter(eventDateString, eventDateStringBis);
				Intent intent = new Intent(this, MapFilterActivity.class);
				intent.putStringArrayListExtra("ids", (ArrayList<String>) ids);
				Event e = new Event();
				e.setDate(eventDateString);
				Calendar cal1 = Calendar.getInstance();
				cal1.setTime(e.getDate());
				cal1.set(Calendar.HOUR_OF_DAY, 0);
				cal1.set(Calendar.MINUTE, 1);
				String from = cal1.get(Calendar.DATE) + "/"
						+ (cal1.get(Calendar.MONTH) + 1);
				e.setDate(eventDateStringBis);
				Calendar cal2 = Calendar.getInstance();
				cal2.setTime(e.getDate());
				cal2.set(Calendar.HOUR_OF_DAY, 23);
				cal2.set(Calendar.MINUTE, 59);
				String to = cal2.get(Calendar.DATE) + "/"
						+ (cal2.get(Calendar.MONTH) + 1);
				String title = "da " + from + " a " + to;
				if (cal1.getTimeInMillis() < cal2.getTimeInMillis()) {
					if (ids.size() == 0) {
						noResults();
					} else {
						intent.putExtra("filter", title);
						startActivity(intent);
					}
				} else {
					Toast.makeText(this, R.string.wrong_interval,
							Toast.LENGTH_SHORT).show();
				}

			}
		} else {
			Toast.makeText(this, R.string.both_date_needed, Toast.LENGTH_SHORT)
					.show();
		}

	}

	public void listFilter(View view) {
		List<String> ids = new ArrayList<String>();
		if (cbBand.isChecked()) {
			if (!editText.getText().toString().equals("")) {
				ids = bandFilter(editText.getText().toString());
				if (ids.size() == 0) {
					noResults();
				} else {
					Intent intent = new Intent(this, EventListActivity.class);
					intent.putStringArrayListExtra("ids",
							(ArrayList<String>) ids);
					intent.putExtra("filter", editText.getText().toString());
					startActivity(intent);
				}
			} else {
				Toast.makeText(this, R.string.band_needed, Toast.LENGTH_SHORT)
						.show();
			}
		} else if (cbVenue.isChecked()) {
			if (!editText.getText().toString().equals("")) {
				ids = venueFilter(editText.getText().toString());
				if (ids.size() == 0) {
					noResults();
				} else {
					Intent intent = new Intent(this, EventListActivity.class);
					intent.putStringArrayListExtra("ids",
							(ArrayList<String>) ids);
					intent.putExtra("filter", editText.getText().toString());
					startActivity(intent);
				}

			} else {
				Toast.makeText(this, R.string.venue_needed, Toast.LENGTH_SHORT)
						.show();
			}
		} else if (cbDate.isChecked()) {
			if (eventDateString != null) {
				ids = dateFilter(eventDateString);
				if (ids.size() == 0) {
					noResults();
				} else {
					Intent intent = new Intent(this, EventListActivity.class);
					intent.putStringArrayListExtra("ids",
							(ArrayList<String>) ids);
					intent.putExtra("filter", editText.getText().toString());
					startActivity(intent);

				}
			} else {
				Toast.makeText(this, R.string.date_needed, Toast.LENGTH_SHORT)
						.show();
			}
		} else if (cbDateInterval.isChecked()) {
			if (eventDateString != null && eventDateStringBis != null) {
				ids = intervalDateFilter(eventDateString, eventDateStringBis);

				Intent intent = new Intent(this, EventListActivity.class);
				intent.putStringArrayListExtra("ids", (ArrayList<String>) ids);
				Event e = new Event();
				e.setDate(eventDateString);
				Calendar cal1 = Calendar.getInstance();
				cal1.setTime(e.getDate());
				cal1.set(Calendar.HOUR_OF_DAY, 0);
				cal1.set(Calendar.MINUTE, 1);
				String from = cal1.get(Calendar.DATE) + "/"
						+ (cal1.get(Calendar.MONTH) + 1);
				e.setDate(eventDateStringBis);
				Calendar cal2 = Calendar.getInstance();
				cal2.setTime(e.getDate());
				cal2.set(Calendar.HOUR_OF_DAY, 23);
				cal2.set(Calendar.MINUTE, 59);
				String to = cal2.get(Calendar.DATE) + "/"
						+ (cal2.get(Calendar.MONTH) + 1);
				String title = "da " + from + " a " + to;
				if (cal1.getTimeInMillis() < cal2.getTimeInMillis()) {
					if (ids.size() == 0) {
						noResults();
					} else {
						intent.putExtra("filter", title);
						startActivity(intent);
					}
				} else {
					Toast.makeText(this, R.string.wrong_interval,
							Toast.LENGTH_SHORT).show();
				}
			}
		} else {
			Toast.makeText(this, R.string.both_date_needed, Toast.LENGTH_SHORT)
					.show();
		}

	}

	public void noResults() {
		AlertDialog.Builder alertb = new AlertDialog.Builder(this);
		alertb.setTitle(R.string.no_result_title);
		alertb.setPositiveButton(R.string.ok, null);
		alertb.setMessage(R.string.no_result_message);
		alertb.setIcon(R.drawable.ic_alerts_and_states_error);
		AlertDialog alert = alertb.create();
		alert.show();
	}

}
